package me.yuzho.study.concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

class ExceptionThread2 implements Runnable {

    @Override
    public void run() {
        
        Thread t = Thread.currentThread();
        System.out.println(t + " is running ...");
        System.out.println("Its exception handler =" + t.getUncaughtExceptionHandler());
        
        throw new RuntimeException();
        

    }
}

class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("Caught " + e + " from " + t);
    }
    
}

class HandlerThreadFactory implements ThreadFactory {

    
    @Override
    public Thread newThread(Runnable r) {
        System.out.println(this + " creating a new thread");
        
        Thread t = new Thread(r); // Tip: create a thread which execute task defined by Runnable r
        
        System.out.println(t + " created");
        
        t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
        
        System.out.println("Exception Handler =" + t.getUncaughtExceptionHandler());
        
        return t;
    }
    
}

public class CaptureUncaughtException {

    public static void main(String[] args) {
        
        ExecutorService exec = Executors.newCachedThreadPool(new HandlerThreadFactory());
        exec.execute(new ExceptionThread2());
    }

}
